package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * devicedateService业务层处理
 *
 * @author LiuLi
 * @date 2025-08-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询devicedate
     *
     * @param id devicedate主键
     * @return devicedate
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询devicedate列表
     *
     * @param deviceData devicedate
     * @return devicedate
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增devicedate
     *
     * @param deviceData devicedate
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改devicedate
     *
     * @param deviceData devicedate
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除devicedate
     *
     * @param ids 需要删除的devicedate主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除devicedate信息
     *
     * @param id devicedate主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 接收IOT平台上报的数据
     *
     * @param iotMsgNotifyData 物联网平台上报数据
     */
    @Override
    public void receiveIotDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1. 判断设备是否存在
        String iotid = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotid));
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        //2.获取到设备上报的数据，一个设备可以有多个service
        iotMsgNotifyData.getBody().getServices().forEach(service -> {
            //3. 处理上报时间
            String eventTime = service.getEventTime();
            LocalDateTime localDateTime = ZonedDateTime
                    .parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            //4.创建map存储数据
            Map<String, Object> map = new HashMap<>();
            //5.遍历service中的属性，封装成map
            service.getProperties().forEach((key, value) -> {
                map.put(key, value);
            });
            //6.创建list存储数据
            List<DeviceData> deviceDataList = new ArrayList<>();
            //7.遍历map中的数据，封装成DeviceData对象
            map.forEach((key, value) -> {
                DeviceData deviceData = DeviceData.builder()
                        .iotId(device.getIotId())
                        .deviceName(device.getDeviceName())
                        .nickname(device.getNickname())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .dataValue(value + "")
                        .alarmTime(localDateTime)
                        .build();
                deviceDataList.add(deviceData);
            });
            //8. 批量保存
            saveBatch(deviceDataList);
            //9. 缓存数据
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, iotid, JSON.toJSONString(deviceDataList));
        });
    }


    /**
     * 分页查询设备数据
     *
     * @param deviceDataPageReqDto 设备数据分页查询请求模型
     * @return 设备数据分页查询结果
     */
    @Override
    public TableDataInfo pageQuery(DeviceDataPageReqDto deviceDataPageReqDto) {
        //1. 分页查询
        Page<DeviceData> page = new Page<>(deviceDataPageReqDto.getPageNum(), deviceDataPageReqDto.getPageSize());
        //2. 构建查询条件
        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //3. 模糊查询设备名称
        if (StringUtils.isNotEmpty(deviceDataPageReqDto.getDeviceName())) {
            lambdaQueryWrapper.like(DeviceData::getDeviceName, deviceDataPageReqDto.getDeviceName());
        }
        //4. 精确查询功能名称
        if (StringUtils.isNotEmpty(deviceDataPageReqDto.getFunctionId())) {
            lambdaQueryWrapper.eq(DeviceData::getFunctionId, deviceDataPageReqDto.getFunctionId());
        }
        //5. 时间范围查询
        if (ObjectUtils.isNotEmpty(deviceDataPageReqDto.getStartTime()) && ObjectUtils.isNotEmpty(deviceDataPageReqDto.getEndTime())) {
            lambdaQueryWrapper.between(DeviceData::getAlarmTime, deviceDataPageReqDto.getStartTime(), deviceDataPageReqDto.getEndTime());
        }
        //6. 分页查询
        page = page(page, lambdaQueryWrapper);
        //7. 封装分页对象
        return getTableDataInfo(page);

    }

    /**
     * 封装分页对象
     *
     * @param page
     * @return
     */
    @NotNull
    private static TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }
}

